<template>
  <div id="home">
    <div class="el-header">
      <!-- <div class="v-header-logo">
        <img :src="`${$store.state.baseUrl}img/logo.png`" />
      </div> -->
      <el-menu
        :default-active="$route.matched[1].path"
        mode="horizontal"
        router
        class="ps-left"
        style="border-bottom: 0"
      >
        <el-menu-item index="/model_manage"
          ><i class="iconfont icon-model"></i> 模型管理</el-menu-item
        >
        <!--                <el-menu-item index="/connect"><i class="iconfont icon-joint"></i> 导入</el-menu-item>-->
        <!--                <el-menu-item index="/model"><i class="iconfont icon-model"></i> 配置</el-menu-item>-->
        <el-menu-item index="/instance_manage"
          ><i class="iconfont icon-joint"></i> 实例管理</el-menu-item
        >
        <el-menu-item index="/knowledge"
          ><i class="iconfont icon-document"></i> 知识查询</el-menu-item
        >
      </el-menu>

      <!--            <div class="header-content-userDetail">-->
      <!--                <img :src="`${$store.state.baseUrl}img/user-logo.png`">-->
      <!--                <el-dropdown trigger="click" @command="handleCommand">-->
      <!--                        <span class="el-dropdown-link">-->
      <!--                            <span>{{appInfo.admin_account}}<br>{{appInfo.admin_name}}</span>-->
      <!--                            <i class="el-icon-arrow-down"></i>-->
      <!--                        </span>-->
      <!--                    <el-dropdown-menu slot="dropdown">-->
      <!--                        <el-dropdown-item command="editPassword">修改密码</el-dropdown-item>-->
      <!--                        <el-dropdown-item command="logout">退出</el-dropdown-item>-->
      <!--                    </el-dropdown-menu>-->
      <!--                </el-dropdown>-->
      <!--            </div>-->

      <ul class="header-content-menu" style="float: right; margin-right: 20px">
        <li>
          <el-button
            :type="appInfo.authState"
            @click="$store.dispatch('authImport')"
            v-show="appInfo.auth"
            round
            size="mini"
            style="padding: 4px 15px"
            >授权过期时间：{{ appInfo.auth }}
          </el-button>
        </li>
        <!-- <li>
          <el-popover
            :disabled="message.popoverDisabled"
            placement="bottom"
            width="270"
            title="消息"
            trigger="click"
          >
            <ul class="message-list" ref="message-list">
              <li v-if="message.lexicon">
                <span>外部词典更新中...</span>
              </li>
              <li v-if="message.learn">
                <span>分析模型学习中：</span>
                <el-progress
                  :percentage="message.studyProgressPercentage"
                ></el-progress>
              </li>
            </ul>
            <el-badge
              :hidden="message.popoverDisabled"
              :value="message.badgeValue"
              class="item"
              slot="reference"
            >
              <a href="javascript:;"><i class="iconfont icon-hint"></i></a>
            </el-badge>
          </el-popover>
        </li> -->
        <!--                <li>-->
        <!--                    <a href="#"><i class="iconfont icon-setting"></i></a>-->
        <!--                </li>-->
      </ul>

      <el-dialog title="修改密码" :visible.sync="form.visible" width="450px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="旧密码：" prop="passWord">
            <el-input
              type="password"
              v-model="form.passWord"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码：" prop="newPassWord">
            <el-input
              type="password"
              v-model="form.newPassWord"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="renewPassWord">
            <el-input
              type="password"
              v-model="form.renewPassWord"
              maxlength="20"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              form.visible = false;
              $refs['form'].resetFields();
            "
            >取 消</el-button
          >
          <el-button type="primary" @click="editPassword">确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <router-view></router-view>
  </div>
</template>

<script>
import $ from "jquery";
import "../../public/style/index.less";

export default {
  name: "home",
  data: function () {
    const samePassword = (rule, value, callback) => {
      if (value !== this.form.newPassWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      form: {
        visible: false,
        passWord: "",
        newPassWord: "",
        renewPassWord: "",
      },
      rules: {
        passWord: [{ required: true, message: "旧密码不能为空" }],
        newPassWord: [{ required: true, message: "新密码不能为空" }],
        renewPassWord: [
          { required: true, message: "确认密码不能为空" },
          { validator: samePassword, trigger: "blur" },
        ],
      },
      websock: null,
      message: {
        popoverDisabled: true,
        studyProgressPercentage: 0,
        lexicon: false,
        learn: false,
        badgeValue: 0,
      },
      appInfo: {},
    };
  },
  methods: {
    handleCommand(command) {
      switch (command) {
        case "editPassword":
          this.form.visible = true;
          break;
        case "logout":
          sessionStorage.clear();
          window.location.href = "/";
          break;
      }
    },
    editPassword() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$store.dispatch("ajax", {
            url: "api/updatePassWord",
            method: "put",
            data: {
              passWord: this.form.passWord,
              newPassWord: this.form.newPassWord,
            },
            succeed: () => {
              this.$refs["form"].resetFields();
              this.form.visible = false;
            },
          });
        } else {
          return false;
        }
      });
    },
    initWebSocket() {
      //初始化weosocket
      const wsuri = this.$store.state.wsApi + "websocket"; //ws地址
      this.websock = new WebSocket(wsuri);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      console.log("WebSocket连接成功");
    },
    websocketonerror() {
      //错误
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) {
      //数据接收
      const redata = JSON.parse(e.data);
      //注意：长连接我们是后台直接1秒推送一条数据，
      //但是点击某个列表时，会发送给后台一个标识，后台根据此标识返回相对应的数据，
      //这个时候数据就只能从一个出口出，所以让后台加了一个键，例如键为1时，是每隔1秒推送的数据，为2时是发送标识后再推送的数据，以作区分

      if (redata.type && redata.type === "learn") {
        if (redata.data.state === 1 && redata.data.percent < 100) {
          this.message.learn = true;
          this.message.studyProgressPercentage =
            Math.round(redata.data.percent * 100) / 100;
        } else {
          this.message.learn = false;
          this.message.studyProgressPercentage = 0;

          if (this.$route.path === "/model/training_model") {
            location.reload();
          }
        }
      }
      if (redata.type && redata.type === "lexicon") {
        if (redata.data.state === 1) {
          this.message.lexicon = true;
        } else {
          this.message.lexicon = false;
        }
      }
      this.updateMessage();
    },
    websocketsend(agentData) {
      //数据发送
      this.websock.send(agentData);
    },
    websocketclose(e) {
      //关闭
      console.log("connection closed (" + e.code + ")");
    },
    updateMessage() {
      setTimeout(() => {
        this.message.badgeValue = $(this.$refs["message-list"]).children(
          "li"
        ).length;
        if (this.message.badgeValue > 0) {
          this.message.popoverDisabled = false;
        } else {
          this.message.popoverDisabled = true;
        }
      }, 200);
    },
  },
  mounted() {
    this.initWebSocket();

    this.$store.dispatch("ajax", {
      url: "api/appInfo",
      method: "get",
      succeed: (res) => {
        this.appInfo = res.appInfo;
        const expireDate = new Date(this.appInfo.auth);
        const nowDate = new Date();
        const diff = expireDate.getTime() - nowDate.getTime();

        if (diff < 90 * 24 * 3600 * 1000) {
          this.appInfo.authState = "warning";
        } else if (diff < 30 * 24 * 3600 * 1000) {
          this.appInfo.authState = "danger";
        } else {
          this.appInfo.authState = "success";
        }
      },
    });
  },
};
</script>
